const router = require('koa-router')();
const { sequelize } = require('../common/dbs')

const linksModel = require("../models/links")
const links = linksModel(sequelize);
const linkTypeModel = require("../models/linkType")
const linkType = linkTypeModel(sequelize);

var Sequelize = require('sequelize')
var Op = Sequelize.Op;

// 统一返回的公共字段
const attributes = ['id', 'desc', 'created_at', 'url', 'title']
const typeAttributes = ['id', 'name', 'created_at']

// 查询分类列表
router.get('/list', async (ctx) => {
    try {
        let reqQuery = ctx.request.query;
        let reData = await linkType.findAll(
            {
                order: [  //排序 DESC ASC
                    ['sort', 'DESC']
                ],
                attributes: typeAttributes
            }
        );
        ctx.success(reData)
    } catch (err) {
        console.log(err)
        ctx.fail(0, err)
    }
})

// 查询分类分页列表
router.get('/pageList', async (ctx) => {
    try {
        let reqQuery = ctx.request.query;

        let reData = await linkType.findAndCountAll(
            {
                where: {
                    name: {
                        [Op.like]: `%${reqQuery.name}%`
                    }
                },
                order: [  //排序 DESC ASC
                    ['sort', 'DESC']
                ],
                limit: reqQuery.limit ? parseInt(reqQuery.limit) : 10,
                offset: reqQuery.page > 0 ? (parseInt(reqQuery.page) - 1) * 10 : 0,
            }
        );
        console.log(reData)
        ctx.success(reData)
    } catch (err) {
        ctx.fail(0, err)
    }
})

// 分类编辑或者添加
router.post('/editOrAdd', async (ctx) => {
    try {
        ctx
            .validateBody("name")
            .required("分类名不能为空")
            .isString()
            .trim()

        let reqBody = ctx.request.body;
        let requestData = null
        let msgType = '添加'
        let b = {
            name: reqBody.name,
            sort: reqBody.sort,
        }

        if (reqBody.id) {
            delete b.id
            // 编辑
            requestData = await
                linkType.update(b, {
                    where: {
                        id: reqBody.id
                    }
                })
            msgType = '修改'
        } else {
            b['id'] = getuuid(12)
            // 新增
            requestData = await
                linkType.create(b)
        }
        if (requestData) {
            ctx.success(msgType + '成功')
        } else {
            ctx.fail(0, msgType + '失败')
        }

    } catch (err) {
        ctx.fail(0, err && err.message)
    }
})

// 分类删除
router.delete('/del/:id', async (ctx) => {
    try {
        if (!ctx.params.id) {
            ctx.fail(0, 'id不能为空')
        }
        let requestData = await
            linkType.destroy({
                where: {
                    id: ctx.params.id
                }
            })
        if (requestData > 0) {
            ctx.success('删除成功')
        } else {
            ctx.fail(0, '已删除,或者不存在')
        }
    } catch (err) {
        ctx.fail(0, err)
    }
})

linkType.hasMany(links, { foreignKey: 'type_id', targetKey: 'id', as: 'links' });
// 查询带分类的列表
router.get('/listAndType', async (ctx) => {
    try {

        let reqQuery = ctx.request.query;
        let reData = await linkType.findAll(
            {
                order: [  //排序 DESC ASC
                    ['sort', 'DESC']
                ],
                attributes: typeAttributes,
                include: [
                    {
                        model: links,
                        as: 'links',
                        attributes: attributes
                    },
                ],
            }
        );
        ctx.success(reData)
    } catch (err) {
        console.log(err)
        ctx.fail(0, err)
    }
})

function getuuid(max = 32) {
    let s = [];
    let hexDigits = "0123456789abcdef";
    for (var i = 0; i < max; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    if (max > 13) {
        s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
    }
    if (max > 18) {
        s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
    }
    // s[8] = s[13] = s[18] = s[23] = "-";
    var uuid = s.join("");
    return uuid;
}


module.exports = router.routes();


